package com.fine.hair.manage.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fine.hair.comm.enums.RewardsPunishmentType;
import com.fine.hair.comm.model.Commission;
import com.fine.hair.comm.model.Order;
import com.fine.hair.comm.model.RewardsPunishment;
import com.fine.hair.manage.mapper.CommissionMapper;
import com.fine.hair.manage.mapper.OrderMapper;
import com.fine.hair.manage.mapper.RewardsPunishmentMapper;
import com.fine.hair.manage.service.CommissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>${Description}</p>
 *
 * @author mouseyCat
 * @date 2020/10/29 23:00
 */
@Service
public class CommissionServiceImpl extends ServiceImpl<CommissionMapper, Commission> implements CommissionService {

    @Resource
    private RewardsPunishmentMapper rewardsPunishmentMapper;

    @Resource
    private CommissionMapper commissionMapper;

    @Autowired
    private Snowflake snowflake;

    @Resource
    private OrderMapper orderMapper;

    @Override
    public void syncCommission(Order order) {
        List<Commission> commissions =
                commissionMapper.selectList(new LambdaQueryWrapper<Commission>().orderByAsc(Commission::getSectionStart).orderByAsc(Commission::getSectionEnd));
        // 查出该订单之前有多少个已完成订单
        Integer count = orderMapper.selectCompletedOrderCount(order.getUserId());
        for (Commission commission : commissions) {
            // 判断是否在区间
            // 此处存在这种情况:用户配置两个区间 如 1-100 5-100 ，此使用户用户第 6 单仍然以 1-100 区间提成，遵循最小原则
            if (count >= commission.getSectionStart() && count <= commission.getSectionEnd()) {
                BigDecimal proportion = order.getItemPrice().multiply(new BigDecimal(commission.getProportion().toString())).divide(new BigDecimal("100"), BigDecimal.ROUND_HALF_UP);
                RewardsPunishment rewardsPunishment = new RewardsPunishment();
                rewardsPunishment.setId(snowflake.nextId());
                rewardsPunishment.setAmount(proportion);
                rewardsPunishment.setRemark("订单提成");
                rewardsPunishment.setType(RewardsPunishmentType.PROPORTION.getCode());
                rewardsPunishment.setUserId(order.getTechnicianId());
                rewardsPunishment.setBranchId(order.getBranchId());
                rewardsPunishmentMapper.insert(rewardsPunishment);
            }
            break;
        }
    }
}


